﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Preyla
{
    public partial class FormServers : Form
    {
        int Rights;

        IDatabase DBManager = new AccessManager(Properties.Settings.Default.ConnectionString);

        List<int> DeletedServers = new List<int>();

        int ConfigurationID = 0;

        Color DefaultColor;
        Color AlternatingDefaultColor;

        public int GetConfigurationID
        {
            get { return ConfigurationID; }
        }

        public FormServers(int Rights)
        {
            InitializeComponent();

            this.Rights = Rights;
        }

        private void ConfigurationsTable_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2 && e.RowIndex != -1)
            {
                bool b = Save();

                if (!b)
                {
                    return;
                }

                if (ServersTable[0, e.RowIndex].Value != null)
                {
                    int ID = Int32.Parse(ServersTable[0, e.RowIndex].Value.ToString());

                    FormConfigurations formConfigurations = new FormConfigurations(ID, ServersTable[1, e.RowIndex].Value.ToString(), Rights);

                    formConfigurations.ShowDialog();

                    if (formConfigurations.GetConfigurationID != 0)
                    {
                        ConfigurationID = formConfigurations.GetConfigurationID;

                        Close();
                    }
                }
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FormServers_Load(object sender, EventArgs e)
        {
            DBManager.Open();

            DefaultColor = ServersTable.DefaultCellStyle.BackColor;
            AlternatingDefaultColor = ServersTable.AlternatingRowsDefaultCellStyle.BackColor;

            Read();

            if (Rights == 2)
            {
                //ServersTable.AllowUserToAddRows = false;
                ServersTable.AllowUserToDeleteRows = false;
                ServersTable.ReadOnly = true;
            }
        }

        void Read()
        {
            string[][] Data = DBManager.ExecuteReader("SELECT DISTINCT Objects.ID, Objects.[Name] FROM Objects, Links WHERE Duplication = 0 AND Links.ID = Objects.ID;");

            for (int i = 0; i < Data.Length; i++)
            {
                ServersTable.Rows.Add();
                ServersTable[0, ServersTable.Rows.Count - 2].Value = Data[i][0];
                ServersTable[1, ServersTable.Rows.Count - 2].Value = Data[i][1];
                ServersTable[2, ServersTable.Rows.Count - 2].Value = "Edit...";
            }
        }

        bool Save()
        {
            for (int i = 0; i < ServersTable.Rows.Count - 1; i++)
            {
                try
                {
                    if (ServersTable[1, i].Value == null)
                    {
                        MessageBox.Show("Server name is empty");

                        return false;
                    }

                    string Name = ServersTable[1, i].Value.ToString().Trim();

                    if (String.IsNullOrEmpty(Name))
                    {
                        MessageBox.Show("Server name is empty");

                        return false;
                    }

                    for (int j = 0; j < ServersTable.Rows.Count - 1; j++)
                    {
                        if (i == j) continue;
                        if (Name.CompareTo(ServersTable[1, j].Value.ToString()) == 0)
                        {
                            MessageBox.Show("Server name " + Name + " is used twice");

                            return false;
                        }
                    }

                    if (ServersTable[0, i].Value != null)
                    {
                        DBManager.ExecuteNonQuery(String.Format("UPDATE Objects SET [Name]='{1}' WHERE ID = {0};", ServersTable[0, i].Value, ServersTable[1, i].Value));
                    }
                    else
                    {
                        DBManager.ExecuteNonQuery(String.Format("INSERT INTO Objects ([Name]) VALUES ('{0}')", ServersTable[1, i].Value));

                        //int ID = DBManager.ExecuteScalar("SELECT ID FROM Objects WHERE Name = '" + ServersTable[1, i].Value + "';");
                        int ID = DBManager.ExecuteScalar("SELECT @@IDENTITY;");
                        
                        ServersTable[0, i].Value = ID;

                        DBManager.ExecuteNonQuery("INSERT INTO Links (ID, ObjectID, Duplication) VALUES (" + ID + ", NULL, 0)");
                    }
                }
                catch (Exception ex)
                { }
            }

            for (int i = 0; i < DeletedServers.Count; i++)
            {
                DBManager.ExecuteNonQuery("DELETE FROM Objects WHERE ID = " + DeletedServers[i]);

                string [][]Data = DBManager.ExecuteReader("SELECT ObjectID FROM Links WHERE ID = " + DeletedServers[i]);

                for (int j = 0; j < Data.Length; j++)
                {
                    if (Data[j][0] != "")
                    {
                        DBManager.ExecuteNonQuery("DELETE FROM Objects WHERE ID = " + Data[j][0]);
                        DBManager.ExecuteNonQuery("DELETE FROM Links WHERE ID = " + Data[j][0]);
                    }
                }

                DBManager.ExecuteNonQuery("DELETE FROM Links WHERE ID = " + DeletedServers[i]);
            }

            DeletedServers.Clear();

            return true;
        }

        private void FormServers_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool b = Save();

            if (!b)
            {
                DialogResult dialogResult = MessageBox.Show("There are errors during saving. Quit without saving?", "Warning", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes)
                {
                    DBManager.Close();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void ServersTable_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Delete row?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DeletedServers.Add(Int32.Parse(ServersTable[0, e.Row.Index].Value.ToString()));
                }
                else
                {
                    e.Cancel = true;
                }               
            }
            catch (Exception ex)
            { } 
        }

        private void ServersTable_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            ServersTable[2, ServersTable.Rows.Count - 2].Value = "Edit...";
        }

        private void SearchText_TextChanged(object sender, EventArgs e)
        {
            Search(ServersTable, SearchText.Text);
        }

        void Search(DataGridView datagrid, string Search)
        {
            for (int i = 0; i < datagrid.Rows.Count - 1; i++)
            {
                if (i % 2 == 0)
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        datagrid[j, i].Style.BackColor = DefaultColor;
                    }
                }
                else
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        datagrid[j, i].Style.BackColor = AlternatingDefaultColor;
                    }
                }
            }

            if (SearchText.Text != "")
            {
                for (int i = 0; i < datagrid.Rows.Count - 1; i++)
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        if (datagrid[j, i].Value.ToString().Contains(Search))
                        {
                            for (int k = 1; k < datagrid.Columns.Count; k++)
                            {
                                datagrid[k, i].Style.BackColor = Color.FromArgb(180, 255, 180);
                            }
                        }
                    }
                }
            }
        }
    }
}
